from rest_framework import serializers

from .models import RunResult
from pathlib import Path

class RunResultSerializer(serializers.ModelSerializer):
    report_url = serializers.SerializerMethodField()
    log_url = serializers.SerializerMethodField()
    yaml_url = serializers.SerializerMethodField()

    class Meta:
        model = RunResult
        # fields = (
        #     "__all__"  # 取model中所有的字段。如果只是取部分，就 ("a","b") 元组的方式
        # )
        exclude = ["path"]  # 排除参数中的path

    def get_report_url(self, obj):
        path = Path(str(obj.path)) # 获取：upload_yaml/1748014411.8458302  例子 上传文件的路径
        dir_name = path.name # 获取 1748014411.8458302
        return f"http://127.0.0.1:8000/api/case/static/{dir_name}/report/allure/index.html"

    def get_log_url(self, obj):
        path = Path(str(obj.path)) # 获取：upload_yaml/1748014411.8458302  例子 上传文件的路径
        dir_name = path.name # 获取 1748014411.8458302
        return f"http://127.0.0.1:8000/api/case/static/{dir_name}/logs/pytest.log"

    def get_yaml_url(self, obj):
        path = Path(str(obj.path)) # 获取：upload_yaml/1748014411.8458302  例子 上传文件的路径
        dir_name = path.name # 获取 1748014411.8458302
        return f"http://127.0.0.1:8000/api/case/static/{dir_name}/test_api.yaml"